package cn.scantd.core;

import java.io.File;
import java.util.Map;

import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;

import com.alibaba.fastjson.JSON;

import cn.scantd.core.ast.JavaFileAST;
import cn.scantd.core.attrs.Scope;
import cn.scantd.kit.FileKit;

public class ASTBuilder {

    @SuppressWarnings("rawtypes")
    public static void build(File file, Scope scope, String[] sources, String[] classpath, String[] encodes, String output, Callback callback) {
        byte[] input = FileKit.readFromFile(file);
        
        ASTParser astParser = ASTParser.newParser(AST.JLS8);
        astParser.setResolveBindings(true);
        astParser.setKind(ASTParser.K_COMPILATION_UNIT);
        
        astParser.setBindingsRecovery(true);
        
        Map options = JavaCore.getOptions();
        JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options);
        astParser.setCompilerOptions(options);
        
        String unitName = file.getName();
        astParser.setUnitName(unitName);
        
        astParser.setEnvironment(classpath, sources, encodes, true);
        astParser.setSource(new String(input).toCharArray());

        CompilationUnit result = (CompilationUnit) (astParser.createAST(null));
        
        JavaFileAST javaFileAST = new JavaFileAST(scope);
        result.accept(javaFileAST);
        
        String dicPath = FileKit.convertToDic(result.getPackage().getName().getFullyQualifiedName());
        File targetDic = new File(output + File.separator + dicPath);
        if (!targetDic.exists() || targetDic.isFile()) {
            targetDic.mkdirs();
        }
        
        if (callback != null) {
        	// callback
        	callback.go(targetDic.getAbsolutePath(), javaFileAST.getJavaType());
        } else {
        	FileKit.writeToFile(new File(targetDic + File.separator + unitName.replace(".java", ".txt")), JSON.toJSONString(javaFileAST.getJavaType(), true));
        }
    }
    
}
